#include "ScriptableLua.h"


#include "../OgreFrameWork.h"


ScriptableLua::ScriptableLua()
{
    //ctor
    L=0;
    m_textScript.clear();

    m_isScriptInitialized=false;
    m_isScriptDefined=false;




}

ScriptableLua::~ScriptableLua()
{
    //dtor
    lua_close(L);
    L=0;
}


/** @brief clearScripts
  *
  * @todo: document this function
  */
void ScriptableLua::runClearInScript()
{
    lua_getglobal(L,"clear");
    //if top of stack is not a function then onLoad does not exist
    if(lua_isfunction(L, -1)) lua_call(L,0,0);
    lua_pop( L, -1 );
}

/** @brief isInitialized
  *
  * @todo: document this function
  */
bool ScriptableLua::isScriptInitialized()
{
    return m_isScriptInitialized;
}



/** @brief update
  *
  * @todo: document this function
  */
void ScriptableLua::runUpdateInScript(double timeSinceLastFrame)
{
    lua_getglobal(L,"update");
    //if top of stack is not a function then onLoad does not exist
    if(lua_isfunction(L, -1)) lua_call(L,0,0);
    lua_pop( L, -1 );
}

/** @brief initScript
  *
  * @todo: document this function
  */
void ScriptableLua::runInitInScript()
{
    int error;

    //run init() function if it exists
    lua_getglobal(L,"init");
    //if top of stack is not a function then onLoad does not exist
    if(lua_isfunction(L, -1))
    if(lua_pcall(L, 0, 0,error))
        OgreFramework::getSingletonPtr()->m_pLog->logMessage("ERROR Lua : "+std::string(lua_tostring(L, -1)));
        else
    lua_pop( L, -1 );
  //  lua_pop( L, -1 );



}


/** @brief isScriptDefined
  *
  * @todo: document this function
  */
bool ScriptableLua::isScriptDefined()
{
    return m_isScriptDefined;
}

/** @brief loadScript
  *
  * @todo: document this function
  */
void ScriptableLua::loadScript(std::string _script)
{
    L = lua_open();
//     load the libs
    luaL_openlibs(L);

    if (luaL_dofile(L,_script.c_str())==0)
    {
        // il y a eu une erreur dans le script
        m_isScriptInitialized=true;
        m_isScriptDefined=true;

    }
    else
    OgreFramework::getSingletonPtr()->m_pLog->logMessage("ERROR loading Lua Script");


}

